package com.tsunami.base;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsunami.exception.code.ExceptionCode;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 公共返回结果
 *
 * @author lx
 * @date 2020-01-19 17:54
 */
@Data
public class R implements Serializable {
    /**
     * 数据数量
     **/
    Integer count;
    /**
     * 代码
     **/
    Integer code;
    /**
     * 信息
     **/
    String msg;
    /**
     * 返回数据
     **/
    private Map<String, Object> extra = new HashMap<>(1);

    /**
     * 构造方法私有化，里面的方法都是静态方法
     * 达到保护属性的作用
     */
    private R() {
    }

    /**
     * 使用链式编程
     *
     * @return R
     */
    public static R ok() {
        R results = new R();
        results.setCode(ExceptionCode.SUCCESS.getCode());
        results.setMsg(ExceptionCode.SUCCESS.getMsg());
        return results;
    }

    public static R error() {
        R results = new R();
        results.setCode(ExceptionCode.FATL.getCode());
        results.setMsg(ExceptionCode.FATL.getMsg());
        return results;
    }

    public R count(Integer count) {
        this.setCount(count);
        return this;
    }

    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R msg(String msg) {
        this.setMsg(msg);
        return this;
    }

    public R exCode(ExceptionCode ec) {
        this.setCode(ec.getCode());
        this.setMsg(ec.getMsg());
        return this;
    }

    public R data(String key, Object val) {
        Map<String, Object> map = new HashMap<>(2);
        map.put(key, val);
        this.setExtra(map);
        return this;
    }

    public R data(Map<String, Object> map) {
        this.setExtra(map);
        return this;
    }

    public R data(Object val) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", val);
        this.setExtra(map);
        return this;
    }

    public R data(Page page) {
        // 获取当前页的数据集
        Object rows = page.getRecords();
        Map<String, Object> map = new HashMap<>(1);
        map.put("list", rows);
        // 获取满足条件的总记录数
        long total = page.getTotal();
        this.setCount(Integer.valueOf(Long.toString(total)));
        this.setExtra(map);
        return this;
    }
    /*链式编程结束**/

}
